import numpy as np
import DRW_library as dl
from multiprocessing import Pool
from time import perf_counter
start=perf_counter()

def mainprocess(m):
    baseline=100*1.122**m
    epochs=int(1.122**m/cadence)
    re=np.array([])
    for k in range(N):       
        np.random.seed(seed[m*N+k])
        #t=np.linspace(0,baseline,epochs)+np.random.uniform(-0.13,0.13,epochs)
        t=np.sort(np.random.randint(0,baseline,epochs)+
                  np.random.uniform(-0.13,0.13,epochs))
        y=dl.DRW_process(t,tau,0.2,17)
        ls_sdss=[]
        lsigma=[]
        for i in range(epochs):
            s=np.sqrt(0.004**2+np.exp(1.63*(y[i]-22.55)))
            #s=np.sqrt(0.013**2+np.exp(2*(y[i]-23.36)))
            lsigma.append(s)
            ls_sdss.append(np.random.normal(y[i],s,1)[0])
        s_sdss=np.array(ls_sdss)
        sigma=np.array(lsigma)
        try:
            re=np.append(re,dl.DRW_fit(t,s_sdss,sigma))
        except:
            print('Err',m)
            continue
    re.resize((N,2))
    re=re.T.flatten()  
    print('[',m,']')
    return np.concatenate(([epochs],re))
    
#BEGIN
tau=100
cadence=1
N=10000
seed=np.random.randint(1,2**31-1,200*N)
print('cadence=',cadence,'N=',N)
if __name__ == '__main__':
    pool=Pool(61)
    l=np.array(pool.map(mainprocess, range(61)))
    pool.close()
    pool.join()    
np.savetxt('cadence1.txt',l,fmt='%.4f')
print('time=',perf_counter()-start)
#END    
